import React, {Component} from 'react'
import * as PropTypes from "prop-types";
import classNames from 'classnames'
import {ErrorMessage} from '../Validation'
import {RadioGroupStore} from "@/components/Radio";
import {StoreManager} from "@/stores";
import {observer} from 'mobx-react'

@observer
export class RadioGroup extends Component {
    static contextTypes = {
        formSettings: PropTypes.object
    }

    static propTypes = {
        id: PropTypes.string,
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired,
        value: PropTypes.string,
        disabled: PropTypes.bool,
        inline: PropTypes.bool,
        validations: PropTypes.arrayOf(PropTypes.func)
    }

    static defaultProps = {
        validations: [],
        inline: true,
        showErrors: true
    }

    constructor(props, context) {
        super(props, context)
        const parent = context.formSettings && context.formSettings.store
        this.store = StoreManager.create(new RadioGroupStore(props), parent)

    }

    componentWillUnmount() {
        StoreManager.delete(this.store)
    }

    handleClick = (options) => {
        this.store.changeValue(options.value)
    }

    render() {
        let {
            name,
            className,
            showErrors,
            inline
        } = this.props
        const {invalid, errors, options, value} = this.store
        return (
            <div name={name} className={classNames('radio-group', {inline}, className)}>
                {options.map(option =>
                    <div key={option.value}
                         className={classNames('radio-button', {'checked': value === option.value})}>
                        <label
                            onClick={() => this.handleClick(option)}>
                            <i className="radio-icon"></i>
                            {option.label ? <span className="radio-label">{option.label}</span> : null}
                        </label>
                    </div>)}

                <ErrorMessage showErrors={showErrors} invalid={invalid} errors={errors}/>
            </div>
        )
    }
}